// pages/shop-manage/shop-manage.js
const app = getApp()
const { request } = require("../../utils/request")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    urlPath: "",
    goods: [],
    showAddDialog: false, // 是否显示添加商品对话框
    showUpdateDialog: false,
    newName: "",
    newPrice: "",
    newImage: "",
    fileList: [], // 上传的文件列表
    updateGood: null, // 当前修改的商品
    updateGoodName: "", // 修改商品的名称
    updateGoodPrice: "", // 修改商品的价格
    updateGoodFileList: [], // 修改商品的文件列表
    buttonTop: 400, // 按钮初始位置 - 垂直方向
    buttonLeft: 300, // 按钮初始位置 - 水平方向
    windowWidth: 0, // 屏幕宽度
    windowHeight: 0, // 屏幕高度
    isDragging: false, // 是否正在拖动
    types: [],
    activeKey: 0, // 添加一个默认的活动键值
    secondTypes:[],
  },

  getType(){
    const urlPath = this.data.urlPath
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/goods/types`,
      method: "GET",
    }).then(
      (res) => {
        console.log(res.data)
        this.setData({
          types: res.data.data
        })
      }
    ).catch((res)=>{
      console.log("获取商品类型失败", res)
    })
  },

  // 按钮触摸开始事件
  buttonTouchStart: function (e) {
    this.startX = e.touches[0].clientX
    this.startY = e.touches[0].clientY
    this.setData({
      isDragging: true,
    })
  },

  // 按钮触摸移动事件
  buttonTouchMove: function (e) {
    if (!this.data.isDragging) return

    const moveX = e.touches[0].clientX - this.startX
    const moveY = e.touches[0].clientY - this.startY

    let buttonTop = this.data.buttonTop + moveY
    let buttonLeft = this.data.buttonLeft + moveX

    // 限制按钮不超出屏幕边界 (更新为50px的按钮尺寸)
    if (buttonLeft < 0) buttonLeft = 0
    if (buttonLeft > this.data.windowWidth - 50) buttonLeft = this.data.windowWidth - 50
    if (buttonTop < 0) buttonTop = 0
    if (buttonTop > this.data.windowHeight - 50) buttonTop = this.data.windowHeight - 50

    this.setData({
      buttonTop,
      buttonLeft,
    })

    this.startX = e.touches[0].clientX
    this.startY = e.touches[0].clientY
  },

  // 按钮触摸结束事件
  buttonTouchEnd: function () {
    this.setData({
      isDragging: false,
    })
  },

  // 显示修改商品对话框
  showUpdateDialog(event) {
    const item = event.currentTarget.dataset.item
    this.setData({
      showUpdateDialog: true,
      updateGood: item,
      updateGoodName: item.name,
      updateGoodPrice: item.price,
      updateGoodFileList: item.image ? [{ url: item.image }] : [],
    })
  },

  // 关闭修改商品对话框
  closeUpdateDialog() {
    this.setData({
      showUpdateDialog: false,
      updateGood: null,
      updateGoodName: "",
      updateGoodPrice: "",
      updateGoodFileList: [],
    })
  },

  // 提交修改商品
  updateGood() {
    const { updateGood, updateGoodName, updateGoodPrice, updateGoodFileList } = this.data
    if (!updateGoodName || !updateGoodPrice || !updateGoodFileList.length) {
      wx.showToast({
        title: "请填写完整信息",
        icon: "none",
      })
      return
    }

    const requestData = {
      id: updateGood.id,
      name: updateGoodName,
      price: updateGoodPrice,
      image: updateGoodFileList[0].url,
    }

    request({
      url: `${app.globalData.baseUrl}/${this.data.urlPath}/goods/`,
      method: "PUT",
      data: requestData,
    })
      .then((res) => {
        console.log("修改商品成功:", res.data)
        wx.showToast({
          title: "修改成功",
          icon: "success",
        })
        this.closeUpdateDialog()
        this.getItems() // 刷新商品列表
      })
      .catch((error) => {
        console.error("修改商品失败:", error)
        wx.showToast({
          title: "修改失败",
          icon: "none",
        })
      })
  },

  // 文件上传后处理（修改商品）
  afterReadUpdate(event) {
    const { file } = event.detail
    const _fileList = [...this.data.updateGoodFileList]

    let files = file
    if (!Array.isArray(files)) {
      files = [files]
    }

    files.forEach((item) => {
      item.keyId = Math.random() * 10
      item.isDeleted = false
      item.isUploadSucc = 0 // 开始上传
      _fileList.push(item)

      wx.uploadFile({
        url: `${app.globalData.baseUrl}/upload`,
        filePath: item.url,
        name: "file",
        formData: { user: "test" },
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data)
          if (uploadRes.statusCode === 200 && data.code === 1) {
            item.isUploadSucc = 1 // 上传成功
            item.url = data.data // 更新文件 URL
            this.setData({
              updateGoodFileList: _fileList,
            })
          } else {
            item.isUploadSucc = -1 // 上传失败
            this.setData({ updateGoodFileList: _fileList })
            wx.showToast({
              title: "文件上传失败",
              icon: "none",
            })
          }
        },
        fail: (error) => {
          console.error("文件上传失败", error)
          item.isUploadSucc = -1 // 上传失败
          this.setData({ updateGoodFileList: _fileList })
          wx.showToast({
            title: "文件上传失败",
            icon: "none",
          })
        },
      })
    })

    this.setData({ updateGoodFileList: _fileList })
  },

  // 删除图片（修改商品）
  delImgHandleUpdate(e) {
    const { index } = e.currentTarget.dataset
    const _fileList = [...this.data.updateGoodFileList]
    _fileList.splice(index, 1)
    this.setData({
      updateGoodFileList: _fileList,
    })
  },

  // 显示添加商品对话框
  showAddDialog() {
    this.setData({ showAddDialog: true })
  },

  // 关闭添加商品对话框
  closeAddDialog() {
    this.setData({ showAddDialog: false })
  },

  // 提交添加商品
  submitAddGoods() {
    const { newImage, newName, newPrice, fileList } = this.data
    if (!newName || !newPrice || !fileList.length || !newImage) {
      wx.showToast({
        title: "请填写完整信息",
        icon: "none",
      })
      return
    }

    this.addGoodsToServer()
  },

  cleanNewData() {
    console.log("数据清理")
    this.setData({
      newImage: "",
      newName: "",
      newPrice: "",
      fileList: [],
    })
  },

  // 添加商品到服务器
  addGoodsToServer() {
    const { newImage, newName, newPrice, urlPath } = this.data
    //封装请求数据
    const requestData = {
      name: newName, //
      image: newImage,
      price: newPrice,
    }
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/goods`,
      method: "POST",
      data: requestData,
    })
      .then((res) => {
        console.log("添加商品成功:", res.data)
        wx.showToast({
          title: "添加成功",
          icon: "success",
        })
        this.cleanNewData()
        this.closeAddDialog()
        this.getItems() // 刷新商品列表
      })
      .catch((error) => {
        console.error("添加商品失败:", error)
        wx.showToast({
          title: "添加失败",
          icon: "none",
        })
      })
  },

  // 输入框值变化时更新数据
  onNameChange(e) {
    this.setData({
      "newGoods.name": e.detail.value,
    })
  },
  onPriceChange(e) {
    this.setData({
      "newGoods.price": e.detail.value,
    })
  },

  // 文件上传前置校验 不能上传动图
  beforeRead(event) {
    const { file, callback } = event.detail
    const regex = /\.gif$/i
    if (regex.test(file.url)) {
      callback(false)
      wx.showToast({
        title: "不支持上传动图类型的图片，请重新上传",
        icon: "none",
        duration: 2000,
      })
      return
    }
    callback(true)
  },

  // 文件上传后处理
  afterRead(event) {
    const { file } = event.detail
    const _fileList = [...this.data.fileList]

    // 如果 file 不是数组，将其包装成一个数组
    let files = file
    if (!Array.isArray(files)) {
      files = [files]
    }

    files.forEach((item) => {
      item.keyId = Math.random() * 10
      item.isDeleted = false
      item.isUploadSucc = 0 // 开始上传
      _fileList.push(item)

      // 上传文件到服务器
      wx.uploadFile({
        url: `${app.globalData.baseUrl}/upload`, // 替换为你的后端接口地址
        filePath: item.url,
        name: "file",
        formData: { user: "test" },
        success: (uploadRes) => {
          console.log("uploadRes", uploadRes)
          const data = JSON.parse(uploadRes.data)
          if (uploadRes.statusCode === 200 && data.code === 1) {
            // 上传成功，更新文件列表
            item.isUploadSucc = 1 // 上传成功
            item.url = data.data // 更新文件 URL
            this.setData({
              fileList: _fileList,
              newImage: data.data,
            })
          } else {
            // 上传失败
            item.isUploadSucc = -1 // 上传失败
            this.setData({ fileList: _fileList })
            wx.showToast({
              title: "文件上传失败",
              icon: "none",
            })
          }
        },
        fail: (error) => {
          console.error("文件上传失败", error)
          item.isUploadSucc = -1 // 上传失败
          this.setData({ fileList: _fileList })
          wx.showToast({
            title: "文件上传失败",
            icon: "none",
          })
        },
      })
    })

    this.setData({ fileList: _fileList })
  },

  // 删除图片
  delImgHandle(e) {
    const { index } = e.currentTarget.dataset
    console.log(index)
    const _fileList = [...this.data.fileList]
    _fileList.splice(index, 1)
    this.setData({ fileList: _fileList })
  },

  // 删除前确认
  delImgBefore(e) {
    wx.showModal({
      title: "删除提示",
      content: "请确认是否删除该图片",
      success: (res) => {
        if (res.confirm) {
          this.delImgHandle(e)
        }
      },
    })
  },
  deleteGoods(e) {
    wx.showModal({
      title: "删除提示",
      content: "请确认是否删除该商品",
      success: (res) => {
        if (res.confirm) {
          this.deleteGoodsConfirm(e)
        }
      },
    })
  },
  deleteGoodsConfirm(e) {
    const { urlPath } = this.data
    const id = e.currentTarget.dataset.id
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/goods/${id}`,
      method: "DELETE",
    })
      .then((res) => {
        wx.showToast({
          title: "删除成功",
          duration: 1000,
          icon: "success",
        })
        this.getItems()
      })
      .catch(() => {
        wx.showToast({
          title: "删除失败",
          icon: "none",
        })
      })
  },
  updateStatus(e) {
    const { urlPath } = this.data
    const id = e.currentTarget.dataset.id
    const goods = this.data.goods.find((item) => item.id === id)
    const status = goods.status === 0 ? 1 : 0

    request({
      url: `${app.globalData.baseUrl}/${urlPath}/goods/${id}`,
      method: "PUT",
      data: { status: status },
    })
      .then((res) => {
        this.getItems()
        wx.showToast({
          title: "操作成功",
          duration: 1000,
          icon: "success",
        })
      })
      .catch(() => {
        console.log("updateStatus失败")
        wx.showToast({
          title: "操作失败",
          icon: "none",
        })
      })
  },
  getPath() {
    try {
      const tokenName = wx.getStorageSync("tokenName")
      console.log("tokenName:", tokenName)
      if (tokenName === "usertoken") {
        this.setData({ urlPath: "employee" })
      } else if (tokenName === "admintoken") {
        this.setData({ urlPath: "admin" })
      } else {
        this.setData({ urlPath: "sadmin" })
      }
    } catch (e) {
      console.error("获取 tokenName 失败:", e)
      // this.setData({ urlPath: "sadmin" }); // 默认值
    }
  },

  getItems() {
    const urlPath = this.data.urlPath
    request({
      url: `${app.globalData.baseUrl}/${urlPath}/goods/manage`,
      method: "GET",
    })
      .then((res) => {
        console.log(res.data)
        this.setData({
          goods: res.data.data,
        })
      })
      .catch((res) => {
        console.log("获取商品数据失败", res)
        wx.showToast({
          title: "获取商品数据失败",
          icon: "none",
        })
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取屏幕尺寸
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      windowWidth: systemInfo.windowWidth,
      windowHeight: systemInfo.windowHeight,
      // 设置按钮初始位置在右下角
      buttonLeft: systemInfo.windowWidth - 80,
      buttonTop: systemInfo.windowHeight - 200,
    })

    this.getPath()
    this.getItems()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init()
    this.getType()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
})
